import traceback
import logging

try:
    from simplejson import dumps
except:
    from json import dumps

from datetime import datetime
from django.db.models.query import QuerySet
from django.forms.models import model_to_dict
from django.template.context import RequestContext
from django.conf import settings
from django.http import HttpResponse, HttpResponseServerError, Http404
from django.shortcuts import render_to_response

logger = logging.getLogger()

def dumps_handler(object):

    if isinstance(object, datetime):
        return object.isoformat()
    if isinstance(object, QuerySet):
        items = []
        for item in object:
            items.append(model_to_dict(item))
        return items

def render(tpl='', type='html', is_root_html=False):
    def renderer(func):
        def wrapper(request, *args, **kwargs):
            try:
                result = func(request, *args, **kwargs)
                if (not 'admin/' in tpl) and (not is_root_html):
                    template = "%s/%s" % (settings.LIVE_ENGINE_TEMPLATE, tpl)
                else:
                    template = tpl

                if isinstance(result, dict):
                    if type == 'html':
                        result['LIVE_ENGINE_DEFAULT_TITLE'] = settings.LIVE_ENGINE_DEFAULT_TITLE
                        result['LIVE_ENGINE_DEFAULT_META_DESCRIPTION'] = settings.LIVE_ENGINE_DEFAULT_META_DESCRIPTION
                        result['LIVE_ENGINE_DEFAULT_META_KEYWORDS'] = settings.LIVE_ENGINE_DEFAULT_META_KEYWORDS
                        result['LIVE_ENGINE_TEMPLATE'] = settings.LIVE_ENGINE_TEMPLATE

                        response = render_to_response(template, result, context_instance=RequestContext(request))

                    elif type == 'json':
                        response = HttpResponse(dumps(result, default=dumps_handler), mimetype="application/json")

                    elif type == 'xml':
                        response = render_to_response(template, result, context_instance=RequestContext(request))
                        response['Content-Type'] = "application/xhtml+xml"

                    else:
                        raise Exception("Undefined type: %s" % type)

                    return response

                else:
                    return result
                
            except Http404:
                raise Http404
            
            except Exception, e:
                traceback.print_exc()
                logger.error(traceback.format_exc())
                return HttpResponseServerError()

        return wrapper
    return renderer